<?php

namespace Biz\service\FineGoodsBrokeNews;

use Biz\model\FineGoodsBrokeNews\FineGoodsBrokeNewsFavouriteLogModel;

class FineGoodsBrokeNewsFavouriteLogService
{
    /** @var string 增加收藏数 */
    const TYPE_INCREASE = "1";

    /** @var string 减少收藏数 */
    const TYPE_DECREASE = "2";

    /**
     * 获取每个小时收藏数
     * @param string $datetime
     * @return array|bool
     */
    public static function getHourFavouriteLog(string $datetime)
    {
        return FineGoodsBrokeNewsFavouriteLogModel::getLog($datetime);
    }

    /**
     * 添加收藏日志
     * @param int $basic_id
     * @param string $datetime
     * @param int $favNum
     */
    public static function addLog(int $basic_id, string $datetime, int $favNum)
    {
        FineGoodsBrokeNewsFavouriteLogModel::addLog($basic_id, $datetime, $favNum);
    }

    public static function calculateFavCount($basicID, $type)
    {
        $basicID = array_values(array_unique(explode(",", $basicID)));
        $list = FineGoodsBrokeNewsFavouriteLogModel::select(['basic_id'], [
            'basic_id' => $basicID
        ]);
        $exist = array_column($list,'basic_id');
        $diff = array_values(array_diff($basicID, $exist));
        if ($type == self::TYPE_INCREASE) {
            FineGoodsBrokeNewsFavouriteLogModel::increaseFavCount($exist);
        } else {
            FineGoodsBrokeNewsFavouriteLogModel::decreaseFavCount($exist);
        }
        foreach ($diff as $index => $item) {
            FineGoodsBrokeNewsFavouriteLogModel::insert([
                'basic_id' => $item,
                'log_time' => date("Y-m-d H:00:00"),
                'fav_count' => 1
            ]);
        }
        return FineGoodsBrokeNewsFavouriteLogModel::select(['basic_id', 'fav_count'], [
            'basic_id' => $basicID
        ]);
    }
}